package ypmits.data.remoting {
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;

	/**
	 * @author Dave Lenz
	 */
	public class RemotingManager extends EventDispatcher {

		private static var _instance : RemotingManager;
		private var _gateway : String = "http://www.ypmits.nl/admin/_amfphp/gateway.php";
		private var _classpath : String;
		private var _arg : *;
		
		public var data : Array = [];

		
		public function RemotingManager() {
			_instance = this;
		}

		
		public static function get instance() : RemotingManager {
			if (!_instance) {
				_instance = new RemotingManager( );
			}
			return _instance;
		}
		
		
		public function load( ) : void {
			if( !_classpath ) throw new Error( "Error! No 'classpath' is given! Use '<RemotingManager>.classpath = \"blabla\"" );
			if( !_arg ) throw new Error( "Error! No 'arg' is given! Use '<RemotingManager>.arg = \"blabla\"" );
			
			var r : Remoting = new Remoting( _gateway, _classpath, _arg );
			r.addEventListener( Event.COMPLETE, completeHandler );
			r.addEventListener( IOErrorEvent.IO_ERROR, errorHandler );
		}

		
		private function completeHandler( e : Event ) : void {
			data.push( [ Remoting( e.currentTarget ).classpath, Remoting( e.currentTarget ) ] );
			e.stopImmediatePropagation();
			
			var evt : RemotingManagerEvent = new RemotingManagerEvent( RemotingManagerEvent.COMPLETE );
			evt.remotingobject = Remoting( e.currentTarget );
			dispatchEvent( evt );
		}
		
		
		private function errorHandler(event : IOErrorEvent) : void {
			trace("RemotingManager.errorHandler("+[event]+")");
		}

		
		public function retrieveData( classpath : String ) : * {
			for (var i : int = 0; i < data.length; i++) {
				if( classpath == data[i][0]) {
					return data[i][1];
					break;
				}
			}
			return null;
		}
		
		
		public function set gateway(gateway : String) : void {
			_gateway = gateway;
		}
		
		
		public function set classpath(classpath : String) : void {
			_classpath = classpath;
		}
		
		
		public function set arg(arg : *) : void {
			_arg = arg;
		}
	}
}
